package sg.edu.nus.iss.jass.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.DebugGraphics;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import sg.edu.nus.iss.jass.constant.CommonConstants;
import sg.edu.nus.iss.jass.constant.ErrorConstants;
import sg.edu.nus.iss.jass.controller.JobAdvertisementController;
import sg.edu.nus.iss.jass.datastore.exception.DataStoreException;
import sg.edu.nus.iss.jass.dto.Company;
import sg.edu.nus.iss.jass.dto.GeographicalLocation;
import sg.edu.nus.iss.jass.dto.JobAdvert;
import sg.edu.nus.iss.jass.dto.Skill;
import sg.edu.nus.iss.jass.dto.SkillReference;
import sg.edu.nus.iss.jass.exception.ValidationException;
import sg.edu.nus.iss.jass.gui.component.ValidateJTextField;
import sg.edu.nus.iss.jass.persistence.CompanyDAO;
import sg.edu.nus.iss.jass.persistence.LocationDAO;
import sg.edu.nus.iss.jass.persistence.SkillDAO;
import sg.edu.nus.iss.jass.util.Util;
import sg.edu.nus.iss.jass.validation.ValidationRule;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
* author: Tan Pic Cheng
*/
public class JobAdvertisementFormPanel extends FormPanel{
	
	private JobAdvertisementController jobAdvertisementController;
	private MainFrame mainframe;
	
	private List<Skill> skillList;
	private List<SkillReference> skillsList = null;
	private List<GeographicalLocation> locations = null;
	private List<Company> companies = null;
	
	private JLabel createdDateLbl;
	private JLabel displayCreatedDateLbl;
	private JLabel jobTitleLbl; 
	private JLabel jobPositionLbl;
	private JLabel jobDescriptionLbl;
	private JLabel locationCountryLbl;
	private JLabel companyLbl;
	private JLabel startDateLbl;
	private JLabel salaryLbl;
	private JLabel hideSalaryLbl;
	
	private ValidateJTextField jobTitleTxtField; 
	private ValidateJTextField positionTxtField;
	private ValidateJTextField startDateTxtField;
	private ValidateJTextField skillExpTxtField[];
	
	private JTextArea descriptionTxtArea;
	private	JComboBox  skillListCbx[];
	private JComboBox  skillLevelCbx[]; 	
	private JComboBox countryCbx;
	private JComboBox salaryCbx;
	private JComboBox hideSalaryCbx;
	private JComboBox companyCbx;
	
    private final int NO_OF_SKILLS_ROWS = 5;
	
	String skills[] = {"JAVA", ".NET", "TIBCO"};
	String skillRefIds[] = null;	
	
	String skillLevels[] = {"Select","Beginner", "Intermediate", "Advanced"};
	
	public JobAdvertisementFormPanel(MainFrame mainframe, ActionPanel actionPanel,
			HeaderPanel headerPanel, List<SkillReference> skillsList, List<GeographicalLocation> locations, 
			List<Company> companies) {
		
		super(mainframe, actionPanel, headerPanel);
		this.skillsList = skillsList;
		this.locations = locations;
		this.companies = companies;
		this.mainframe = mainframe;
		
		initGUI();
	}
	
	private void initGUI() {
		try {
			setPreferredSize(new Dimension(800, 1550));
			this.setLayout(null);
			this.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
			this.setFont(new java.awt.Font("Arial",0,12));
			{
				createdDateLbl = new JLabel("Created Date:");
				{
					createdDateLbl = new JLabel("Created Date:");
					createdDateLbl.setBounds(22, 29, 91, 21);
					this.add(createdDateLbl);
				}
				{
					Date date = new Date();
					displayCreatedDateLbl = new JLabel(Util.getStringFromdate(date));
					displayCreatedDateLbl.setBounds(159, 29, 150, 21);
					this.add(displayCreatedDateLbl);
				}
				{
					jobTitleLbl = new JLabel("Job Title:");
					jobTitleLbl.setBounds(22, 75, 150, 21);
					this.add(jobTitleLbl);
				}
				{
					jobTitleTxtField = new ValidateJTextField("Job Title", ValidationRule.NOT_NULL);
					jobTitleTxtField.setBounds(159, 73, 150, 25);
					jobTitleTxtField.setColumns(10);
					this.add(jobTitleTxtField);
				}
				{			
					jobPositionLbl = new JLabel("Job Position:");
					jobPositionLbl.setBounds(20, 123, 148, 21);
					this.add(jobPositionLbl);
				}
				{			
					positionTxtField = new ValidateJTextField("Job Position", ValidationRule.NOT_NULL);
					positionTxtField.setBounds(159, 121, 150, 25);
					positionTxtField.setColumns(10);
					this.add(positionTxtField);
				}
				{			
					jobDescriptionLbl = new JLabel("Job Description:");
					this.add(jobDescriptionLbl);
					jobDescriptionLbl.setBounds(19, 173, 150, 21);
				}
				{			
					descriptionTxtArea = new JTextArea();
					descriptionTxtArea.setBounds(159, 173, 150, 139);
					descriptionTxtArea.setLineWrap(true);
					//descriptionTxtArea.setWrapStyleWord(true);
					this.add(descriptionTxtArea);
				}     	
				{
					skills = getSkillReferenceArray();
					JPanel skillsPanel = createSkillsPanel();
					skillsPanel.setBounds(22, 330, 650, 300);
					this.add(skillsPanel);
				}        		
				{			
					locationCountryLbl = new JLabel("Location Country:");
					locationCountryLbl.setBounds(361, 173, 150, 21);
					this.add(locationCountryLbl);
				}
				{			
					List<GeographicalLocation> list = locations;
					int size = list.size();           

					String[] locationList = new String[size];
					int i = 0;

					String name = null;

					for(GeographicalLocation g: list){
						name = g.getCountry();
						locationList[i] = name;
						i++;
					}            
					countryCbx = new JComboBox();
					countryCbx.setModel(new DefaultComboBoxModel(locationList));
					countryCbx.setBounds(557, 171, 150, 25);
					this.add(countryCbx);
				}
				{			
					companyLbl = new JLabel("Company Name:");
					companyLbl.setBounds(361, 220, 150, 21);
					this.add(companyLbl);
				}
				{	
					List<Company> list = companies;
					int size = list.size();           

					String[] companyList = new String[size];
					int i = 0;

					String name = null;

					for(Company c: list){
						name = c.getName();
						companyList[i] = name;
						i++;
					}            
					companyCbx = new JComboBox();
					companyCbx.setModel(new DefaultComboBoxModel(companyList));
					companyCbx.setBounds(557, 218, 150, 25);
					this.add(companyCbx);
				}               
				{			
					startDateLbl = new JLabel("Start Date:");
					startDateLbl.setBounds(361, 32, 150, 21);
					this.add(startDateLbl);
				}
				{			
					startDateTxtField = new ValidateJTextField("Job Start Date", ValidationRule.NOT_NULL, ValidationRule.DATE);
					startDateTxtField.setBounds(557, 29, 150, 25);
					startDateTxtField.setColumns(10);
					this.add(startDateTxtField);
				}
				{
					salaryLbl = new JLabel("Salary:");
					salaryLbl.setBounds(361, 77, 150, 21);
					this.add(salaryLbl);
				}
				{			
					salaryCbx = new JComboBox();
					salaryCbx.setModel(new DefaultComboBoxModel(CommonConstants.salaryRanges.toArray(new String[0])));
					salaryCbx.setBounds(557, 73, 150, 25);
					this.add(salaryCbx);
				}                
				{			
					hideSalaryLbl = new JLabel("Hide Salary:");
					hideSalaryLbl.setBounds(361, 123, 150, 21);
					this.add(hideSalaryLbl);
				}
				{
					hideSalaryCbx = new JComboBox();
					hideSalaryCbx.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No"}));
					hideSalaryCbx.setBounds(557, 121, 150, 25);
					this.add(hideSalaryCbx);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}  
}	
private JPanel createSkillsPanel() {
	
		JPanel pane = new JPanel(new GridLayout ());
		
		pane.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1.5;
		c.weighty = 0.5;
		c.insets = new Insets(5, 5, 5, 5);
		c.ipady = 10;
		
		
	    c.gridx = 0;
		c.gridy = 0;
		pane.add(new JLabel("Skill"), c);
		
		c.gridx = 1;
		c.gridy = 0;
		pane.add(new JLabel("Skill Level"), c);

		c.gridx = 2;
		c.gridy = 0;
		pane.add(new JLabel("Years Of Experience"), c);
        
		
		skillListCbx = new JComboBox[NO_OF_SKILLS_ROWS];
		int y = 1;
		
		for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
			skillListCbx[i] = new JComboBox (skills);
			c.gridx = 0;
			c.gridy = y++;
			pane.add(skillListCbx[i], c);
		}
		
		skillLevelCbx = new JComboBox[NO_OF_SKILLS_ROWS];
		y = 1;
		for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
			skillLevelCbx[i] = new JComboBox (skillLevels);
			c.gridx = 1;
			c.gridy = y++;
			pane.add(skillLevelCbx[i], c);
		}

		skillExpTxtField = new ValidateJTextField[NO_OF_SKILLS_ROWS];
		y = 1;
		for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
			skillExpTxtField[i] = new ValidateJTextField ("Years Of Experience",ValidationRule.NUMERIC);
			c.ipady = 10;
			c.gridx = 2;
			c.gridy = y++;
			pane.add(skillExpTxtField[i], c);
		}
		
		return pane;
	}
	@Override
public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub

	if(e.getActionCommand().equals("Submit")){
		submit();
	}else if(e.getActionCommand().equals("Reset")){
		reset();
	}		
	return;		
}
private void reset() {
	// TODO Auto-generated method stub
	jobTitleTxtField.setText(""); 
	positionTxtField.setText("");
	startDateTxtField.setText("");					
	descriptionTxtArea.setText("");	
	countryCbx.setSelectedIndex(0);
	salaryCbx.setSelectedIndex(0);
	hideSalaryCbx.setSelectedIndex(0);
	companyCbx.setSelectedIndex(0);
	System.out.println(skillExpTxtField.length + "\n" + skillLevelCbx.length);
			
	for(int i = 0; i < skillExpTxtField.length; i++){
		if(!skillExpTxtField [i].getText().isEmpty())
			skillExpTxtField [i].setText("");
			skillListCbx[i].setSelectedIndex(0);
			skillLevelCbx[i].setSelectedIndex(0);
	}		
}
private void submit() {
	// TODO Auto-generated method stub
	displayConfirmationMsg();		
}
private void displayConfirmationMsg() {
	// TODO Auto-generated method stub
	//default icon, custom title
	if (showConfirmDialog("Job Advert", "Add") == 1) {
		// do nothing as it is cancelled
	} else {
		super.clearMsg();
		confirm();
	}		
}
public void errorMsg(){
	clearMsg();
	showMsg("Add Job Advert Error!", false);
}
public void displaySuccessfulMsg(){
	showMsg("Add Job Advert Success!", true);
}	
@Override
public void show() {
	// TODO Auto-generated method stub
	addFormPanel();
}
public void confirm(){
	try {
		Date creationDate = new Date();
		Date startDate = Util.getDateFromString(startDateTxtField.getValidatedText());
		String description = descriptionTxtArea.getText();
		boolean isHideSalary = getIsHideSalary();
		boolean isWithdrawn = false;		
		boolean status = true;
		String title = jobTitleTxtField.getValidatedText();
		String position = positionTxtField.getValidatedText();
		float minSalary = getMinSalary();
		float maxSalary = getMaxSalary();
		GeographicalLocation geographicalLocation = getJobLocation();

		JobAdvert jobAdvert = new JobAdvert();
		jobAdvert.setCreation(creationDate);
		jobAdvert.setStartDate(startDate);
		jobAdvert.setDescription(description);
		jobAdvert.setIsHideSalary(isHideSalary);
		jobAdvert.setIsWithdrawn(isWithdrawn);
		jobAdvert.setStatus(status);
		jobAdvert.setTitle(title);
		jobAdvert.setPosition(position);
		jobAdvert.setMinSalary(minSalary);
		jobAdvert.setMaxSalary(maxSalary);
		jobAdvert.setCompany(getCompany());
		jobAdvert.setGeographicalLocation(geographicalLocation);
		if(skillValidate()){		
			jobAdvert.setSkills(skillList);	
		}
		jobAdvertisementController.processAddJobAd(jobAdvert);
	} catch (ValidationException e) {
		showMsg(e.getMessage(), false);
	}
}
@SuppressWarnings("unused")
private boolean skillValidate() throws ValidationException{
	
	HashMap<String, Skill> exisitingSkills = new HashMap<String, Skill>();
	
	skillList = new ArrayList<Skill>();
	for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
		
		Skill skill = null;
		if(skillListCbx[i] != null && skillListCbx[i].getSelectedItem() != null){
			
			String tmpSkillName = skillListCbx[i].getSelectedItem().toString();
			
			System.out.println("tmpSkillName:" + tmpSkillName);				
			
			if(!tmpSkillName.equals("Select")){
				
				int tmpSkillIndex = skillListCbx[i].getSelectedIndex();
				String tmpSkillRefId = skillRefIds[tmpSkillIndex]; //ADDED Select as first item
				System.out.println("tmpSkillRefId:" + tmpSkillRefId);
				
				String tmpSkillLevel = skillLevelCbx[i].getSelectedItem().toString();
				System.out.println("tmpSkillLevel:" + tmpSkillLevel);
				
				if(tmpSkillLevel.equals("Select")){
					throw new ValidationException("Please Select Skill Level");
				}
				
				String tmpSkillExp =  skillExpTxtField[i].getValidatedText();
				System.out.println("tmpSkillExp:" + tmpSkillExp);
				if(tmpSkillExp.trim().length() == 0){
					throw new ValidationException("Please enter Years Of Experience");
				}
				
				skill = new Skill();
				skill.setSkillRefId(tmpSkillRefId); 
				skill.setLvl(Util.getSkillLevelCode(tmpSkillLevel));
				skill.setYearOfExp(Integer.parseInt(tmpSkillExp));
				
				if(!exisitingSkills.containsKey(tmpSkillName)){
					skillList.add(skill);
					exisitingSkills.put(tmpSkillName, skill);
				}else {
					throw new ValidationException("Duplicate Skills");
				}
				
			}else if(!skillLevelCbx[i].getSelectedItem().equals("Select") || 
						skillExpTxtField[i].getText().trim().length() > 0){
				
				throw new ValidationException("Incomplete Skill Details ");
			}
		}
	}
	if(skillList.isEmpty()) {
		throw new ValidationException(ErrorConstants.ERROR_NO_SKILL_SPECIFIED);
	}
	return true;		
}	
private String[] getSkillReferenceArray(){		
	
	if(skillsList != null && skillsList.size() > 0){
		skills = new String[skillsList.size() + 1];
		skillRefIds = new String[skillsList.size() + 1];
		int i = 0;
		
		skills[i] = "Select";
		skillRefIds[i] = "";
		i++;
		Iterator<SkillReference> it = skillsList.iterator();
		
		while(it.hasNext()){
			SkillReference skillref = (SkillReference)it.next();
			skills[i] = skillref.getName();
			skillRefIds[i] = skillref.getId();
			i++;
		}
	}		
	return skills;
}	
public String getJobTitle() throws ValidationException{
	return jobTitleTxtField.getValidatedText();
}
public String getJobPosition() throws ValidationException{
	return positionTxtField.getValidatedText();
}
public GeographicalLocation getJobLocation(){
	Object country= (String) countryCbx.getSelectedItem();
	
	for(GeographicalLocation g : this.locations){
		if(g.getCountry().equals(country))
			return g;
	}		
	return null;
}
public Company getCompany() throws ValidationException{
	Object name = (String) companyCbx.getSelectedItem();
	
	for(Company c : this.companies){
		if(c.getName().equals(name))
			return c;
	}		
	return null;
}
public void setController(JobAdvertisementController jobAdvertisementController){
	this.jobAdvertisementController = jobAdvertisementController;
	//this.addJobPanel.setJobAdvertisementController(jobAdvertisementController);
}
public boolean getIsHideSalary(){
	Object st= (String) hideSalaryCbx.getSelectedItem();
	boolean status = ((st.equals("Yes"))? true : false);
	
	return status;		
}
public String[] getSalary(){		
	Object salary = (String)salaryCbx.getSelectedItem();
	String[] sly = ((String) salary).split("-");		
		return sly;		
	}
	public float getMinSalary(){		
		String[] array = getSalary();
		float maxSalary = Float.parseFloat(array[0]);
		return maxSalary;		
	}
	public float getMaxSalary(){		
		String[] array = getSalary();
		float maxSalary = Float.parseFloat(array[1]);
		return maxSalary;		
	}
}
